<template>
  <!-- 公共文件上传组件，包含图片、文件等 -->
  <div class="uploadPage">
    <n-upload
      v-model:file-list="fileList"
      :accept="fileType"
      :max="maxNum"
      show-download-button
      :custom-request="customRequest"
      list-type="image-card"
    >
      上传文件
    </n-upload>
  </div>
</template>

<script setup lang="ts">
import {
  NUpload,
  type UploadCustomRequestOptions,
  type UploadFileInfo,
} from "naive-ui";
const props = defineProps({
  fileType: {
    type: String, //文件类型格式 image-card(照片墙)  image  text
    default: "image-card",
  },
  maxNum: {
    type: Number, //最大上传文件数
    default: 10,
  },
  listType: {
    type: String, //文件形式  .doc,.docx,.pdf,.xls,.xlsx,.zip,.rar,.jpg,.png,.jpeg,.svg,.gif
  },
  uploadFun: {
    type: Function,
    default: () => {},
  },
  file: {
    type: Object as PropType<UploadFileInfo>,
  },
});
const fileList = ref<UploadFileInfo[]>([]);
const { fileType, maxNum, listType, uploadFun } = props;
const emit = defineEmits(["uploadfile", "deletefile"]);
if (props.file) fileList.value.push(props.file);
const customRequest = async ({
  file,
  data,
  headers,
  withCredentials,
  action,
  onFinish,
  onError,
  onProgress,
}: UploadCustomRequestOptions) => {
  const formData = new FormData();
  if (data) {
    Object.keys(data).forEach((key) => {
      formData.append(
        key,
        data[key as keyof UploadCustomRequestOptions["data"]]
      );
    });
  }
  formData.append("file", file.file as File);
  const files = await uploadFun(formData);
  if (files) fileList.value[0] = files;
};
</script>
<style scoped>
.uploadPage {
  width: 100%;
}
</style>
